package com.gin.no_gay_alliance.fragment.topic.list;

import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.nga.enums.FavorAction;
import com.gin.nga.enums.FavorType;
import com.gin.nga.enums.NgaPhpApi;
import com.gin.nga.params.nuke.favorforum.FavorForumEditParam;
import com.gin.nga.response.body.ThreadBody;
import com.gin.nga.response.field.Forum;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.NoticeActivity;
import com.gin.no_gay_alliance.activity.PriMsgActivity;
import com.gin.no_gay_alliance.activity.PrivilegeListActivity;
import com.gin.no_gay_alliance.activity.ReportingRecordActivity;
import com.gin.no_gay_alliance.activity.TopicHistoryActivity;
import com.gin.no_gay_alliance.activity.TopicListActivity;
import com.gin.no_gay_alliance.activity.TopicReadActivity;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.customview.PagerButton;
import com.gin.no_gay_alliance.databinding.FragmentTopicListCommonBinding;
import com.gin.no_gay_alliance.fragment.topic.BaseTopicListFragment;
import com.gin.no_gay_alliance.manager.FavorForumManager;
import com.gin.no_gay_alliance.param.PreparePostParam;
import com.gin.no_gay_alliance.param.SearchArea;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ClipboardUtils;
import com.gin.no_gay_alliance.utils.MenuUtils;
import com.gin.no_gay_alliance.utils.ParcelableUtils;
import com.gin.no_gay_alliance.viewmodel.PostResult;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 版面浏览和合集浏览抽象类
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/5 11:34
 **/
public abstract class AbstractListFragment extends BaseTopicListFragment<FragmentTopicListCommonBinding> implements ActivityResultCallback<ActivityResult> {
    /**
     * 当前版面id, 作为发帖活动参数和操作子版面参数
     */
    protected Long forumId;
    /**
     * 当前版面
     */
    protected Forum forum;
    /**
     * 版头Id
     */
    private long toppedTopicId;
    /**
     * 备选的搜索区域
     */
    private List<SearchArea> searchAreas;
    /**
     * 发帖按钮
     */
    private ImageView postButton;
    /**
     * 启动器，用来启动发帖活动
     */
    private ActivityResultLauncher<Intent> launcher;
    /**
     * 当前合集id, 作为发帖活动参数
     */
    private Long colTid;

    /**
     * 构造方法
     *
     * @param param 参数
     */

    /**
     * 处理发帖完毕的响应
     *
     * @param activityResult 结果
     */
    @Override
    public void onActivityResult(ActivityResult activityResult) {
        Intent intent = activityResult.getData();
        if (intent != null) {
            PostResult result = intent.getParcelableExtra(PostResult.class.getName());
            if (result != null && result.topicId != null) {
                // 打开该主题
                TopicReadActivity.startActivity(getContext(), null, result.topicId);
            }
        }
    }

    /**
     * 提供布局文件中的翻页按钮
     *
     * @return {@link PagerButton}
     */
    @NonNull
    @Override
    protected PagerButton initPagerButton() {
        return b.btnPager;
    }

    /**
     * 提供布局文件中的刷新按钮
     *
     * @return {@link ImageButton}
     */
    @NonNull
    @Override
    protected ImageButton initRefreshButton() {
        return b.btnRefresh;
    }

    /**
     * 提供布局文件中的 主题列表分页ViewPager2
     *
     * @return ViewPager2
     */
    @NonNull
    @Override
    protected ViewPager2 initViewPager2() {
        return b.vp2;
    }

    @Override
    protected void onCreateView() {
        super.onCreateView();
        postButton = b.btnPost;
        postButton.setOnClickListener(this);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this);


        initAdapter(param);
    }

    /**
     * 点击事件统一处理
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        // 发帖按钮
        if (v.getId() == R.id.btn_post) {
            launcher.launch(new PreparePostParam(forumId, colTid).buildIntent(getContext()));
        }
    }

    /**
     * 主题列表分页的查询成功回调
     *
     * @param threadBody 响应结果
     */
    @Override
    protected void onSuccessTopicListRequest(ThreadBody threadBody) {
        super.onSuccessTopicListRequest(threadBody);

        // 更新搜索区域和版头id
        forum = threadBody.getForum();
        if (forum != null) {
            searchAreas = SearchArea.build(forum);
            Log.d(getClass().getSimpleName(), "更新搜索区域: " + searchAreas.stream().map(i -> i.name).collect(Collectors.joining(",")));
            toppedTopicId = forum.getToppedTopicId() != null ? forum.getToppedTopicId() : 0;
            forumId = forum.getForumId();
            colTid = forum.getColTid();
            // 设置标题
            toolbar.setTitle(forum.getColTitle() != null ? forum.getColTitle() : forum.getForumName());
        }
    }

    /**
     * 提供布局文件中的Toolbar
     *
     * @return toolbar
     */
    @Nullable
    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }

    /**
     * 创建选项菜单
     *
     * @param menu     菜单
     * @param inflater 渲染器
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        // 装载提醒、私信菜单
        inflater.inflate(R.menu.base_option_menu, menu);
        // 装载 搜索、版头、关注菜单
        inflater.inflate(R.menu.abstract_list_menu, menu);
        // 复制链接和bbsCode
        inflater.inflate(R.menu.share_menu, menu);
    }

    /**
     * 选项菜单的点击响应
     *
     * @param item 选项
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();

        // 版面权限
        if (itemId == R.id.menu_item_privilege_list) {
            PrivilegeListActivity.startActivity(getContext(), forumId);
        }

        // 我的主题
        if (itemId == R.id.menu_item_user_topic) {
            TopicListParam p = new TopicListParam();
            p.type = TopicListParam.Type.USER_SEARCH;
            p.authorUid = MyApplication.getClient().getUserId();
            p.forumId = String.valueOf(forumId);
            TopicListActivity.startActivity(requireContext(), p);
            return true;
        }
        // 我的回复
        if (itemId == R.id.menu_item_my_reply) {
            TopicListParam p = new TopicListParam();
            p.type = TopicListParam.Type.USER_SEARCH;
            p.authorUid = MyApplication.getClient().getUserId();
            p.forumId = String.valueOf(forumId);
            p.searchReply = true;
            TopicListActivity.startActivity(requireContext(), p);
            return true;
        }
        // 关注版面/合集
        if (itemId == R.id.menu_item_follow) {
            favorForumEdit(FavorAction.add);
            return true;
        }
        // 取消关注版面/合集
        if (itemId == R.id.menu_item_followed) {
            String message = String.format(Locale.CHINA, "确认取消收藏 %s?", param.title);
            AlertDialogUtils.showConfirm(requireContext(), "移除收藏", message, (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    favorForumEdit(FavorAction.del);
                }
            });
            return true;
        }
        // 打开搜索界面
        if (itemId == R.id.menu_item_search && searchAreas != null) {
            TopicListParam p = ParcelableUtils.copy(param);
            p.type = p.type == TopicListParam.Type.COL_LIST ? TopicListParam.Type.COL_SEARCH : TopicListParam.Type.FORUM_SEARCH;
            p.searchAreas = searchAreas;
            // 启动活动
            TopicListActivity.startActivity(requireContext(), p);
            return true;
        }

        //打开版头
        if (itemId == R.id.menu_item_topped_topic) {
            TopicReadActivity.startActivity(getContext(), "版头", toppedTopicId);
        }

        // 复制链接
        String path = MyApplication.getClient().getNgaDomain().domain + NgaPhpApi.thread.path;
        if (itemId == R.id.menu_item_copy_link) {
            if (param.type == TopicListParam.Type.COL_LIST) {
                ClipboardUtils.setText(requireActivity(), path + "?stid=" + param.colTid);
            }
            if (param.type == TopicListParam.Type.FORUM_LIST) {
                ClipboardUtils.setText(requireActivity(), path + "?fid=" + param.forumId);
            }
        }
        // 复制bbsCode
        if (itemId == R.id.menu_item_copy_bbs_code) {
            String title = null;
            if (toolbar != null) {
                title = toolbar.getTitle().toString();
            }


            if (param.type == TopicListParam.Type.COL_LIST) {
                ClipboardUtils.setText(requireActivity(), String.format("[url=%s?stid=%s]%s[/url]", NgaPhpApi.thread.path, param.colTid, title != null ? title : ("合集" + param.colTid)));
            }
            if (param.type == TopicListParam.Type.FORUM_LIST) {
                ClipboardUtils.setText(requireActivity(), String.format("[url=%s?fid=%s]%s[/url]", NgaPhpApi.thread.path, param.forumId, title != null ? title : ("版面" + param.colTid)));
            }
        }

        // 提醒
        if (itemId == R.id.menu_item_noti) {
            NoticeActivity.startActivity(requireContext());
            return true;
        }
        // 私信
        if (itemId == R.id.menu_item_pm) {
            PriMsgActivity.startActivity(requireContext());
            return true;
        }
        // 历史
        if (item.getItemId() == R.id.menu_item_topic_history) {
            TopicHistoryActivity.startActivity(requireContext());
            return true;
        }
// 举报记录
        if (item.getItemId() == R.id.menu_item_reporting_record) {
            ReportingRecordActivity.startActivity(requireContext());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 修改选项菜单项目可见性
     *
     * @param menu 菜单
     */
    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // 版头id大于0时显示版头菜单项
        MenuUtils.setVisible(menu, toppedTopicId > 0, R.id.menu_item_topped_topic);
        // 根据关注状态决定显示的菜单项
        FavorForumManager favorForumManager = MyApplication.app.managerFactory.getFavorForumManager();
        favorForumManager.get(false, data -> {
            List<Long> idList = data.stream().flatMap(g -> g.entries.stream()).map(i -> i.id).collect(Collectors.toList());
            boolean followed = (param.forumId != null && idList.contains(Long.parseLong(param.forumId))) || idList.contains(param.colTid);
            MenuUtils.setVisible(menu, followed, R.id.menu_item_followed);
            MenuUtils.setVisible(menu, !followed, R.id.menu_item_follow);
        });
    }

    /**
     * 修改收藏版面 / 合集
     *
     * @param action 操作
     */
    private void favorForumEdit(FavorAction action) {
        FavorForumEditParam p = colTid != null ? new FavorForumEditParam(action, FavorType.col, colTid) : new FavorForumEditParam(action, FavorType.forum, forumId);
        MyApplication.app.managerFactory.getFavorForumManager().edit(p, handler, requireActivity());
    }
}
